package com.oceansoft.core.common.util.impexp4doc.helper;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.io.SAXReader;

import com.heavenlake.wordapi.Document;
import com.oceansoft.core.common.util.CommonUtilCache;
import com.oceansoft.core.common.util.DatetimeUtil;
import com.oceansoft.core.common.util.ObjectUtil;
import com.oceansoft.core.common.util.StringUtil;
import com.oceansoft.core.common.util.WordUtil;

public class BuildDOCHelper {

	public static String buildDOC(Map<String, Object> configure,
			List<?> record, Map Custom) throws Exception{
		//Document doc = null;
		String docXML = "";
		 org.dom4j.Document  document = null;
		String savePath = CommonUtilCache
				.getValue(CommonUtilCache.KEY_WebRealPath)
				+ "/WEB-INF/classes/" + "sysconfig/impexp/" ;
		String tmpPath = "";
		//模板文件
		File modalFile  = null;
		//模板文件
		File tmpFile  = null;
		
		try{
		String modal = (String) configure.get("modal");

		//doc = new Document();

		if (StringUtil.isNotNull(modal)) {
			String mbPath = savePath + modal;
			//将模板复制一份临时文件
			modalFile = new File(mbPath);
			
			
			tmpPath = savePath+"tmp";
			tmpFile = new File(tmpPath);
			if(!tmpFile.exists())
			{
				tmpFile.mkdir();
			}
			tmpPath += "/moban_"+System.currentTimeMillis()+".txt";
			tmpFile = new File(tmpPath);
			
			FileInputStream fis = new FileInputStream(modalFile);
			FileOutputStream fos = new FileOutputStream(tmpFile);
			byte [] d = new byte[512];
			int rs= -1;
			while((rs = fis.read(d))>0)
			{
				fos.write(d,0,rs);
			}
			fos.close();
			fis.close();
			//doc.open(tmpPath);
		}

		  //模板文件
		SAXReader reader = new SAXReader();
		//模版文件为 ： conf\\testReportTemplate.xml
	    document = reader.read(tmpFile);
		docXML = document.asXML() ;
		
		//读取txt
		/*File f = new File(tmpPath);
		InputStreamReader ir = new InputStreamReader(new FileInputStream(f),"UTF-8");
		
		BufferedReader br = new BufferedReader(ir);
		String lint  = null;
		while((lint = br.readLine())!=null)
		{
			docXML += lint+" ";
		}
		br.close();
		ir.close();
		*/
		Map<String, Object> data = null;
		if (record.isEmpty()) {
			//return doc;
		}
		
		if( record.get(0) instanceof Map<?, ?>)
		{
			data = (Map<String, Object>) record.get(0);
		}
		else
		{
			data = ObjectUtil.Object2Map(record.get(0));
		}
		
		// 加载配置文件
		Map<String, Object> fieldMapping = (Map) configure.get("fieldMapping");
		Iterator<String> keyit = fieldMapping.keySet().iterator();
		while (keyit.hasNext()) {
			String key = keyit.next();
			// 书签信息
			Map bookMarkInfo = (Map) fieldMapping.get(key);
			// 根据书签,替换对应的内容
			String fieldName = (String) bookMarkInfo.get("fieldName");// 数据字段
			String labelName = (String) bookMarkInfo.get("labelName");// 书签名字
			String imagefile = bookMarkInfo.get("imagefile") == null ? "0": "1";
			String pfile = bookMarkInfo.get("pfile") == null ? "0": "1";
			String dataType  = (String) bookMarkInfo.get("dataType");// 字段类型
			

			if ("0".equals(imagefile)) {
				
				String content = "";
				if(StringUtil.isNotNull(dataType))
				{
					String formatter = (String) bookMarkInfo.get("formatter");//需要的格式化处理
					//日期型处理
					if("date".equals(dataType))
					{
						content = DatetimeUtil.formatDate(((Date)data.get(fieldName)), formatter);
					}
					
				}
				else
				{
					content = (String) data.get(fieldName);
				}
				if(null==content)
				{
					content = "";
					if("1".equals(pfile))
					{
						content = WordUtil.createP("");
					}
				}
				try {
					//doc.insertAtBookmark(labelName, content);
					if(docXML.indexOf("$"+labelName)==-1)
					{
						System.out.println("没有找到"+labelName);
					}
					else
					{
						docXML =  docXML.replace("$"+labelName, content);
					}
					
				} catch (Exception e) {
					System.out.println("没有"+labelName+"书签");
					e.printStackTrace();
				}

			} else {
				byte[] imageByte = (byte[]) data.get(fieldName);
				if (null != imageByte) {
					// 先将byte 保存到服务器上,临时目录下
					/*tmpPath = CommonUtilCache
							.getValue(CommonUtilCache.KEY_WebRealPath)
							+ "/WEB-INF/classes/" + "sysconfig/impexp/tmp/";
					File f = new File(tmpPath);
					if (!f.exists()) {
						f.mkdirs();
					}
					tmpPath +=System.currentTimeMillis()+".jpg";
					File imgageFile = getFileFromBytes(imageByte, tmpPath);*/
					try {
						//doc.insertAtBookmark(labelName, imgageFile);
						String impString =  ecodeBase64(imageByte);
						docXML =  docXML.replace("$"+labelName, impString);
						//用完删除
						//imgageFile.delete();
					} catch (Exception e) {
						System.out.println("没有"+labelName+"书签");
						e.printStackTrace();
					}
				}
			}

		}
		}catch (Exception e) {
			/* if(doc!=null)
			 {
				 try {
					    
						doc.close(true);
					} catch (Exception e1) {
						e1.printStackTrace();
					}
		        	doc = null;
		        	
			 }*/
			 e.printStackTrace();
			 throw new Exception();
		
		}
		//System.out.println(docXML);
		//docXML = document.asXML() ;
		//System.out.println(docXML.substring(0,5000));
		return docXML;
	}
	
	private static  String ecodeBase64(byte[] buf) {  
        return null;  
    }  

	private static File getFileFromBytes(byte[] b, String outputFile) {
		BufferedOutputStream stream = null;
		File file = null;
		try {
			file = new File(outputFile);
			FileOutputStream fstream = new FileOutputStream(file);
			stream = new BufferedOutputStream(fstream);
			stream.write(b);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (stream != null) {
				try {
					stream.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
		return file;
	}

	private void java2word(String modal) {
		String imgAFile = "E:\\120.jpg";
		Document doc = null;
		try {
			doc = new Document();
			String p = "F:\\Tomcat6\\webapps\\ROOT\\WEB-INF\\classes\\sysconfig\\"
					+ modal;
			System.out.println("mbpath =  " + p);
			doc.open(p);

			doc.insert(new File(imgAFile));
			String content = new String("第一章：宪政概论".getBytes("iso-8859-1"),
					"GB2312");
			doc.insert("我爱啊");
			// doc.insertAtBookmark("testbookm","第一章：宪政概论",null);
			// doc.insertAtBookmark("testbookm", new java.io.File(imgAFile));
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {

				doc.saveAs("e:\\ttt.doc");
				if (doc != null) {
					doc.close(true);
					doc = null;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}
